package com.example.demo.interceptors;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.example.demo.utils.JWTUtils;
import com.example.demo.utils.PassToken;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            return true;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("code", 401);
        //获取请求头中的令牌
        String token = request.getHeader("Authorization");
        System.out.println("         "+token);
        try {
            JWTUtils.verify(token.substring(token.lastIndexOf(" ")+1));      //验证token     token.substring(token.lastIndexOf(" ")+1)
            return true;                 //放行
        } catch (TokenExpiredException e) {   //验证不通过
            e.printStackTrace();
            map.put("msg", "token过期");
        } catch (Exception e) {                //验证不通过
            e.printStackTrace();
            map.put("msg", "token⽆效");
        }
        //响应到前台: 将map转为json
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}